<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Swoole\Http\Request;
use Swoole\Websocket\Frame;
use Service\WebSocketService\BaseWebSocketService;
use Service\Code\Normal;
class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, Frame $frame): void
    {
        try
        {
            $requestBody = !empty($frame->data) ? @json_decode($frame->data,true) : [];
            BaseWebSocketService::instance()->onMessage($server,$frame->fd,$requestBody);
        } 
        catch ( \Throwable $th)
        {
            //异常处理
            $value = Normal::returnCode(Normal::WS_ERROR,"服务出现异常【{$th->getMessage()},{$th->getFile()},{$th->getLine()}】");
            $server->push($frame->fd,json_encode($value,JSON_UNESCAPED_UNICODE));
        }
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
    }

    public function onOpen($server, Request $request): void
    {
        //$server->push($request->fd, 'Opened');
    }
}